package com.higold.cloud.ui.activity

import android.graphics.Color
import android.graphics.Typeface
import android.os.Build
import android.os.Handler
import android.support.annotation.RequiresApi
import android.support.v4.content.ContextCompat
import android.support.v4.widget.NestedScrollView
import android.support.v7.widget.GridLayoutManager
import android.util.Log
import android.widget.RadioGroup
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.entity.MultiItemEntity
import com.github.mikephil.charting.data.BarData
import com.github.mikephil.charting.data.BarDataSet
import com.github.mikephil.charting.data.BarEntry
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet
import com.github.mikephil.charting.model.GradientColor
import com.gyf.immersionbar.ktx.immersionBar
import com.higold.cloud.MyApplication
import com.higold.cloud.R
import com.higold.cloud.base.BaseActivity
import com.higold.cloud.mvp.contract.AchieveDetailContract
import com.higold.cloud.mvp.model.bean.achievedetailbean.AchieveDetail
import com.higold.cloud.mvp.model.bean.achievedetailbean.Data
import com.higold.cloud.mvp.presenter.AchieveDetailPresenter
import com.higold.cloud.net.exception.ErrorStatus
import com.higold.cloud.showToast
import com.higold.cloud.ui.adapter.AgentDetailAdapter
import com.higold.cloud.view.recyclerview.CurrentAgentItem
import com.scwang.smartrefresh.layout.api.RefreshHeader
import com.scwang.smartrefresh.layout.listener.SimpleMultiPurposeListener
import com.scwang.smartrefresh.layout.util.DensityUtil
import kotlinx.android.synthetic.main.activity_agent_detail_new.*

/**
 *    author : lxz
 *    date   : 2019/8/23 16:41
 *    desc   :
 */
class AgentDetailActivity : BaseActivity(), AchieveDetailContract.View, RadioGroup.OnCheckedChangeListener {

    private val mPresenter by lazy { AchieveDetailPresenter() }
    private var data: com.higold.cloud.mvp.model.bean.Data? = null
    private lateinit var adapter: AgentDetailAdapter
    private lateinit var list: ArrayList<MultiItemEntity>
    private var isfirst: Boolean = true

    private var mOffset = 0
    private var mScrollY = 0

    override fun setAchieveDetail(achieveDetail: AchieveDetail) {
        multipleStatusView.showContent()
        setAdapter(achieveDetail)
    }

    override fun showError(errorMsg: String, errorCode: Int) {
        showToast(errorMsg)
        if (errorCode == ErrorStatus.NETWORK_ERROR) {
            multipleStatusView.showNoNetwork()
        } else {
            multipleStatusView.showError()
        }
    }

    override fun showLoading() {
        multipleStatusView.showLoading()
    }

    override fun dismissLoading() {
    }

    override fun layoutId(): Int = R.layout.activity_agent_detail_new

    override fun start() {
        mPresenter.getAchieveDetail(data!!.user_code)
    }

    override fun initData() {
        data = intent.getSerializableExtra("Agent_Info") as com.higold.cloud.mvp.model.bean.Data
        tv_agent_name.text = data!!.user_name
    }

    override fun initView() {
        mPresenter.attachView(this)
        immersionBar {
            transparentBar()
            titleBar(toolbar)
        }

        scroll_view.post { scroll_view.scrollTo(0, 0) }
        rg_group.setOnCheckedChangeListener(this@AgentDetailActivity)

        setData(12, 50f)

        refreshLayout.setOnRefreshListener {
            Handler().postDelayed({
                mPresenter.getAchieveDetail(data!!.user_code)
            }, 1500)

        }

        refreshLayout.setOnMultiPurposeListener(object : SimpleMultiPurposeListener() {
            override fun onHeaderPulling(header: RefreshHeader?, percent: Float, offset: Int, bottomHeight: Int, extendHeight: Int) {
                mOffset = offset / 2
                parallax.translationY = (mOffset - mScrollY).toFloat()
                toolbar.alpha = 1 - Math.min(percent, 1f)
            }

            override fun onHeaderReleasing(header: RefreshHeader?, percent: Float, offset: Int, bottomHeight: Int, extendHeight: Int) {
                mOffset = offset / 2
                parallax.translationY = (mOffset - mScrollY).toFloat()
                toolbar.alpha = 1 - Math.min(percent, 1f)
            }


        })

        scroll_view.setOnScrollChangeListener(object : NestedScrollView.OnScrollChangeListener {
            private var lastScrollY = 0
            private val h = DensityUtil.dp2px(170f)
            private val color = ContextCompat.getColor(applicationContext, R.color.colorPrimary) and 0x00ffffff
            @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
            override fun onScrollChange(v: NestedScrollView, scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int) {
                var tScrollY = scrollY
                if (lastScrollY < h) {
                    tScrollY = Math.min(h, tScrollY)
                    mScrollY = if (tScrollY > h) h else tScrollY

                    toolbar.setBackgroundColor(255 * mScrollY / h shl 24 or color)
                    toolbar.navigationIcon!!.setTint(255 * mScrollY / h shl 24 or resources.getColor(R.color.colorAccent))
                    parallax.translationY = (mOffset - mScrollY).toFloat()
                }

                lastScrollY = tScrollY
                if (lastScrollY == 0) {
                    tv_header_title.setTextColor(resources.getColor(R.color.color_white))
                    toolbar.navigationIcon!!.setTint(Color.WHITE)
                    immersionBar { statusBarDarkFont(false).navigationBarDarkIcon(false) }
                } else {
                    tv_header_title.setTextColor(resources.getColor(R.color.colorAccent))
                    immersionBar { statusBarDarkFont(true).navigationBarDarkIcon(true) }
                }
            }
        })
        toolbar.setNavigationOnClickListener { onBackPressed() }
    }

    override fun onCheckedChanged(group: RadioGroup?, checkedId: Int) {
        when (group?.checkedRadioButtonId) {
            R.id.rb_month -> {
                refreshLayout.autoRefresh()
            }
            R.id.rb_cumulative -> {
                refreshLayout.autoRefresh()
            }
        }
    }

    private fun setAdapter(achieveDetail: AchieveDetail) {

        if (refreshLayout.isRefreshing) {
            refreshLayout.finishRefresh()
            list = generateData(this.data!!, achieveDetail.data)
            adapter.notifyDataSetChanged()
            rv_achieve.scheduleLayoutAnimation()
        } else {
            list = generateData(this.data!!, achieveDetail.data)
            adapter = AgentDetailAdapter(list)
            adapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM)
            val manager = GridLayoutManager(this@AgentDetailActivity, 3)
            manager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
                override fun getSpanSize(position: Int): Int {
                    return manager.spanCount
                }
            }

            rv_achieve.isNestedScrollingEnabled = false
            rv_achieve.adapter = adapter
            // important! setLayoutManager should be called after setAdapter
            rv_achieve.layoutManager = manager
            adapter.expandAll()

        }
    }

    private fun generateData(data: com.higold.cloud.mvp.model.bean.Data, lastData: Data): ArrayList<MultiItemEntity> {

        val res = ArrayList<MultiItemEntity>()
        val achievedItem = CurrentAgentItem(data)
        for (j in 0 until lastData.current.size) {
            Log.e("data", lastData.current[j].remark)
            achievedItem.addSubItem(lastData.current[j])
        }
        res.add(achievedItem)
        return res
    }

    private fun setData(count: Int, range: Float) {

        val start = 1f

        val values: ArrayList<BarEntry> = ArrayList()

        var i = start.toInt()
        while (i < start + count) {
            val `val` = (Math.random() * (range + 1)).toFloat()

            if (Math.random() * 100 < 25) {
                values.add(BarEntry(i.toFloat(), `val`, resources.getDrawable(R.drawable.ic_user)))
            } else {
                values.add(BarEntry(i.toFloat(), `val`))
            }
            i++
        }

        val set1: BarDataSet

        if (chart.data != null && chart.data.dataSetCount > 0) {
            set1 = chart.data.getDataSetByIndex(0) as BarDataSet
            set1.values = values
            chart.data.notifyDataChanged()
            chart.notifyDataSetChanged()

        } else {
            set1 = BarDataSet(values, "The year 2017")
            set1.setDrawIcons(false)

            val gradientColors: ArrayList<GradientColor> = ArrayList()
            this.let {
                val startColor1 = ContextCompat.getColor(it, R.color.colorAccent)
                val endColor1 = ContextCompat.getColor(it, R.color.colorAccent)

                gradientColors.add(GradientColor(startColor1, endColor1))
            }

            set1.gradientColors = gradientColors

            val dataSets: ArrayList<IBarDataSet> = ArrayList()
            dataSets.add(set1)
            val data = BarData(dataSets)

            data.setValueTextSize(10f)
            data.setValueTypeface(Typeface.createFromAsset(MyApplication.context.assets, "fonts/FZLanTingHeiS-DB1-GB-Regular.TTF"))
            data.barWidth = 0.5f

            chart.data = data
        }
    }

}